package com.hk.core.autoconfigure.data.jpa.tenant;

import com.hk.commons.util.Constants;
import com.hk.core.authentication.api.SecurityContextUtils;
import com.hk.core.authentication.api.TenantInfo;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;

import java.util.Objects;

/**
 * 这个类是由Hibernate提供的用于识别tenantId的类，当每次执行sql语句被拦截就会调用这个类中的方法来获取tenantId
 * 还需要在Spring yml 配置如下属性:
 * spring.data.jpa.properties.hibernate.tenant_identifier_resolver: com.hk.core.autoconfigure.data.jpa.tenant.MultiTenantIdentifierResolver
 *
 * @author Kevin
 * @date 2023-10-12 23:07
 */
@NoArgsConstructor(access = AccessLevel.PUBLIC)
public class MultiTenantIdentifierResolver implements CurrentTenantIdentifierResolver<String> {

    /**
     * 获取 tenantId
     */
    @Override
    public String resolveCurrentTenantIdentifier() {
        if (SecurityContextUtils.isAuthenticated()) {
            TenantInfo tenantInfo = SecurityContextUtils.getPrincipal().getTenantInfo();
            return Objects.nonNull(tenantInfo) && Objects.nonNull(tenantInfo.getTenantId()) ?
                    String.valueOf(tenantInfo.getTenantId()) : Constants.DEFAULT_VALUE;
        }
        return Constants.DEFAULT_VALUE;
    }

    @Override
    public boolean validateExistingCurrentSessions() {
        return true;
    }

    @Override
    public boolean isRoot(String tenantId) {
        return SecurityContextUtils.isAuthenticated() && SecurityContextUtils.getPrincipal().isAdministrator();
    }
}
